<template>
  <div class="w-full">
    <header class="flex items-center justify-between mb-[12px]  border-t border-gray-200 pt-[20px]">
      <div class="mb-[8px] text-[14px] text-[#333] font-medium">时间轴设置</div>
      <el-button :icon="Trash2" link @click="emit('delete')"></el-button>
    </header>
    <el-form ref="formRef" :model="model" :rules="formRules" class="w-full affix-timeline-container"
      label-position="top">
      <div class="mb-[16px] border-b-[1px] border-[#E5E5E5]">
        <el-form-item :label="$t('competition.modules.timeline.backgroundSettings')" label-position="left">
          <el-color-picker v-model="model.bgColor" :style="{ backgroundColor: model.bgColor }" />
        </el-form-item>
      </div>
      <div class="w-full bg-[#fff]">
        <el-button type="primary" @click="addTimelineItem" class="mb-[15px]">新增</el-button>
      </div>
      <draggable :list="model.items" :animation="150" item-key="id" class="w-full" handle=".timeline-row-handle"
        ghost-class="drag-ghost" filter=".no-drag">
        <template #item="{ element: item, index: ti }">
          <div class="w-full">
            <el-form-item class="w-full timeline-form-item" :label="item.title || `节点${ti + 1}`" label-position="top"
              :key="item.id">
              <template #label>
                <div
                  class="timeline-row-handle w-full flex items-center justify-between bg-[#F2F7FD] rounded-[4px] p-[5px] text-[#191919] font-[500] cursor-move">
                  <div @click="handlePlay(item)" class="cursor-pointer select-none no-drag">
                    <Play fill="#595959" class="text-[#595959] play-icon scale-[0.6] inline-block align-top"
                      :class="{ 'play-icon-active': item.isActive }" />
                    <span>{{ item.title || `-` }}</span>
                  </div>
                  <div class="flex items-center">
                    <el-button link :icon="Trash2" class="no-drag" @click="removeTimelineItem(ti)" />
                    <el-button link :icon="GripVertical" class="w-[16px] h-[16px] ml-[12px]" />
                  </div>
                </div>
              </template>
              <template #default>
                <div :class="{ 'hidden': item.isActive === false }"
                  class="w-full pt-[12px] transition-all duration-200">
                  <div class="mb-[20px]">
                    <el-form-item label-width="70px" label-position="left" required :prop="`items.${ti}.title`">
                      <template #label>
                        <span class="leading-[34px] text-[14px] text-[#595959] text-right">{{
                          $t('competition.modules.timeline.title') }}</span>
                      </template>
                      <template #default>
                        <el-input v-model="item.title" maxlength="10" show-word-limit :placeholder="$t('common.inputPhTxt')" />
                      </template>
                    </el-form-item>
                  </div>
                  <div class="mb-[20px]">
                    <el-form-item label-width="70px" label-position="left" required :prop="`items.${ti}.date`">
                      <template #label>
                        <span class="leading-[34px] text-[14px] text-[#595959] text-right">{{
                          $t('competition.modules.timeline.time') }}</span>
                      </template>
                      <template #default>
                        <el-date-picker v-model="item.date" type="date" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
                          :placeholder="$t('common.selectPhTxt')" style="width: 100%"
                          :clearable="false" />
                      </template>
                    </el-form-item>
                  </div>
                  <div class="mb-[20px]">
                    <el-form-item label-width="70px" label-position="left">
                      <template #label>
                        <span class="leading-[34px] text-[14px] text-[#595959]">{{
                          $t('competition.modules.timeline.nodeDescription') }}</span>
                      </template>
                      <template #default>
                        <el-input type="textarea" v-model="item.desc" :rows="10" maxlength="600" show-word-limit
                          :placeholder="$t('common.inputPhTxt')" />
                      </template>
                    </el-form-item>
                  </div>
                </div>
              </template>
            </el-form-item>
          </div>
        </template>
      </draggable>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Play, Trash2, GripVertical } from '@vben/icons';
import { $t } from '#/locales';
import draggable from 'vuedraggable';
import dayjs from 'dayjs';
import type { FormInstance, FormRules } from 'element-plus';

export interface TimelineItem { id: number; title: string; date: string; desc: string; isActive?: boolean }
export interface TimelineState {
  bgColor: string
  items: TimelineItem[]
}

const model = defineModel<TimelineState>({ required: true });
const emit = defineEmits<{ delete: [] }>();

// 表单引用
const formRef = ref<FormInstance>();

// 动态生成验证规则
const formRules = computed<FormRules>(() => {
  const rules: FormRules = {};

  model.value.items.forEach((_, index) => {
    rules[`items.${index}.title`] = [
      { required: true, message: $t('competition.modules.timeline.titleRequired'), trigger: ['blur'] }
    ];
    rules[`items.${index}.date`] = [
      { required: true, message: $t('competition.modules.timeline.dateRequired'), trigger: ['blur'] }
    ];
  });

  return rules;
});

function handlePlay(item: TimelineItem) {
  item.isActive = !item.isActive;
}

function addTimelineItem() {
  model.value.items.push({ id: Date.now(), title: '', date: '', desc: '', isActive: true });
}

function removeTimelineItem(i: number) {
  model.value.items.splice(i, 1);
  // 移除项目后重新验证表单
  setTimeout(() => {
    formRef.value?.clearValidate();
  }, 0);
}

// 验证表单
async function validateForm() {
  if (!formRef.value) return false;
  try {
    await formRef.value.validate();
    return true;
  } catch {
    return false;
  }
}

// 清除验证
function clearValidate() {
  formRef.value?.clearValidate();
}

// 导出验证方法供父组件使用
defineExpose({
  validateForm,
  clearValidate
});


</script>

<style scoped>
.play-icon {
  cursor: pointer;
  transition: transform 0.2s;
}

.play-icon-active {
  transform: rotate(90deg) scale(0.6);
  transition: transform 0.2s;
}

.drag-ghost {
  opacity: 0.6;
}

/* 修复时间轴外层表单项宽度问题 - 只影响最外层的标题容器 */
.timeline-form-item:deep(.el-form-item__label) {
  width: 100% !important;
  padding: 0 !important;
  margin-bottom: 0 !important;
}

.timeline-form-item :deep(.el-form-item__content) .el-form-item.el-form-item--label-left .el-form-item__label {
  width: 70px !important;
  margin-bottom: 0 !important;
  padding-right: 12px !important;
  text-align: right !important;
}
</style>
